package cn.xfdzx.android.apps.shop.activity.login;

import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

import com.luck.picture.lib.tools.ToastUtils;
import com.umeng.socialize.PlatformConfig;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.OnClick;
import cn.xfdzx.android.apps.shop.R;
import cn.xfdzx.android.apps.shop.activity.MainActivity;
import cn.xfdzx.android.apps.shop.activity.UserAgreementActivity;
import cn.xfdzx.android.apps.shop.apps.Constants;
import cn.xfdzx.android.apps.shop.apps.MyApp;
import cn.xfdzx.android.apps.shop.base.BaseMvpActivity;
import cn.xfdzx.android.apps.shop.bean.BaseObjectBean;
import cn.xfdzx.android.apps.shop.bean.LoginBean;
import cn.xfdzx.android.apps.shop.bean.LogininfoBean;
import cn.xfdzx.android.apps.shop.contract.LoginContract;
import cn.xfdzx.android.apps.shop.contract.OtherLoginContract;
import cn.xfdzx.android.apps.shop.evenbus.CarInitDataMessage;
import cn.xfdzx.android.apps.shop.evenbus.IMloginMessage;
import cn.xfdzx.android.apps.shop.evenbus.WeChatCodeEvent;
import cn.xfdzx.android.apps.shop.fragment.OneFragment;
import cn.xfdzx.android.apps.shop.presenter.LoginPresenter;
import cn.xfdzx.android.apps.shop.presenter.OtherLoginPresenter;
import cn.xfdzx.android.apps.shop.presenter.ShopRetailPresenter;
import cn.xfdzx.android.apps.shop.util.EmptyUtil;
import cn.xfdzx.android.apps.shop.util.RegexUtil;
import cn.xfdzx.android.apps.shop.util.Utils;
import cn.xfdzx.android.apps.shop.util.UtilsData;
import cn.xfdzx.android.apps.shop.widget.SendSmsButton;
import cn.xfdzx.android.apps.shop.wxapi.WXEntryActivity;

import static android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP;
import static android.content.Intent.FLAG_ACTIVITY_SINGLE_TOP;
import static cn.xfdzx.android.apps.shop.apps.Constants.APP_TOKEN;

/*
/* 其他手机登录页面
 */
public class MobileLoginActivity extends BaseMvpActivity<OtherLoginPresenter> implements OtherLoginContract.View, TextWatcher {

    @BindView(R.id.iv_back)
    ImageView ivBack;      //标题栏-左边按钮


    @BindView(R.id.et_mobile_phone)
    EditText mobilePhone;   //手机号输入框

    @BindView(R.id.mobile_code)
    EditText mobileCode;    //验证码输入框
    @BindView(R.id.tvSendCode)
    SendSmsButton tvSendCode;  //获取验证码
    @BindView(R.id.tv_phone_hint)
    TextView mobileInfo;     //红字文案提示
    @BindView(R.id.mobile_agreement)
    TextView mobileAgreement;  //用户协议
    @BindView(R.id.mobile_privacy)
    TextView mobilePrivacy;    //隐私权限
    @BindView(R.id.tv_mobile_login)
    TextView mobileLogin;    //登录
    @BindView(R.id.tv_mobile_password)
    TextView mobilePassword;    //密码登陆
    @BindView(R.id.tv_mobile_wx_login)
    ImageView mobileWxLogin;   //微信登录

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);

        }
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_mobilelogin;
    }

    @Override
    public void initView() {
        mPresenter = new OtherLoginPresenter();
        mPresenter.attachView(this);
        EventBus.getDefault().register(this);
        mobilePhone.addTextChangedListener(this);
        mobileCode.addTextChangedListener(this);
        // 发送验证码倒计时监听.
        tvSendCode.setmListener(new SendSmsButton.SDSendValidateButtonListener() {
            @Override
            public void onClickSendValidateButton() {
                if (EmptyUtil.isEmpty(mobilePhone.getText().toString())) {
                    ToastUtils.s(MobileLoginActivity.this,"请输入手机号码");
                    return;
                }
                if (!RegexUtil.isMobileExact(mobilePhone.getText().toString())) {
                    ToastUtils.s(MobileLoginActivity.this,"请输入正确格式的手机号码");
                    return;
                }

                if (mPresenter != null) {
                    mPresenter.sendSms(
                            mobilePhone.getText().toString(),Constants.SMSCODE);
                }
            }

            @Override
            public void onTick() {
            }
        });
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void onError(Throwable throwable) {

    }

    @Override
    public void onLoginCodeSuccess(LogininfoBean bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            APP_TOKEN=bean.getData().getToken();

            UtilsData.getPreference(this,"login").put("token", APP_TOKEN);
            UtilsData.getPreference(this,"login").put("is_store", EmptyUtil.isEmpty(bean.getData().getUserInfo().getIs_store())?0:bean.getData().getUserInfo().getIs_store());
            UtilsData.getPreference(this,"login").put("nickname", EmptyUtil.isEmpty(bean.getData().getUserInfo().getNickname())?"":bean.getData().getUserInfo().getNickname());
            UtilsData.getPreference(this,"login").put("head_url", EmptyUtil.isEmpty(bean.getData().getUserInfo().getAvatar())?"":bean.getData().getUserInfo().getAvatar());
//            Intent intent = new Intent(this, MainActivity.class);
//            intent.addFlags(FLAG_ACTIVITY_CLEAR_TOP);
//            intent.addFlags(FLAG_ACTIVITY_SINGLE_TOP);
//            startActivity(intent);
            EventBus.getDefault().post(new IMloginMessage(1));//通知im登录

            finish();
        } else {
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onSendSmsSuccess(LogininfoBean bean) {
        tvSendCode.setmDisableTime(60);
        tvSendCode.startTickWork();

    }

    @Override
    public void onCheckBindPhoneSuccess(LogininfoBean bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            if (bean.getData().isIs_login()){
                APP_TOKEN=bean.getData().getToken();

                UtilsData.getPreference(this,"login").put("token", APP_TOKEN);
                UtilsData.getPreference(this,"login").put("nickname", EmptyUtil.isEmpty(bean.getData().getUserInfo().getNickname())?"":bean.getData().getUserInfo().getNickname());
                UtilsData.getPreference(this,"login").put("is_store", EmptyUtil.isEmpty(bean.getData().getUserInfo().getIs_store())?0:bean.getData().getUserInfo().getIs_store());
                UtilsData.getPreference(this,"login").put("head_url", EmptyUtil.isEmpty(bean.getData().getUserInfo().getAvatar())?"":bean.getData().getUserInfo().getAvatar());
//                Intent intent = new Intent(this, MainActivity.class);
//                intent.addFlags(FLAG_ACTIVITY_CLEAR_TOP);
//                intent.addFlags(FLAG_ACTIVITY_SINGLE_TOP);
//                startActivity(intent);
                EventBus.getDefault().post(new IMloginMessage(1));//通知im登录

                finish();
            }else {
                Intent intent = new Intent(this, MobileBindActivity.class);
                if (EmptyUtil.isNotEmpty(bean.getData().getHash())){
                    intent.putExtra("loginhash",bean.getData().getHash());
                }
                startActivity(intent);
                finish();
            }
        } else {
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void wechatLoginSuccess(LogininfoBean bean) {

    }

    @OnClick({R.id.iv_back, R.id.mobile_agreement, R.id.mobile_privacy,
            R.id.tv_mobile_login, R.id.tv_mobile_password, R.id.tv_mobile_wx_login})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:       //返回按钮点击
                finish();
                break;
            case R.id.mobile_agreement:   //用户协议点击
                Intent intentuser = new Intent(this,UserAgreementActivity.class);
                intentuser.putExtra("type","0");
                startActivity(intentuser);
                break;
            case R.id.mobile_privacy:    //隐私权限点击
                Intent intentprivacy = new Intent(this,UserAgreementActivity.class);
                intentprivacy.putExtra("type","1");
                startActivity(intentprivacy);
                break;
            case R.id.tv_mobile_login:    //登录点击
                if (EmptyUtil.isEmpty(mobilePhone.getText().toString())) {
                    ToastUtils.s(MobileLoginActivity.this,"请输入手机号码");
                    return;
                }
                if (EmptyUtil.isEmpty(mobileCode.getText().toString())) {
                    ToastUtils.s(MobileLoginActivity.this,"请输入验证码");
                    return;
                }

                if (!RegexUtil.isMobileExact(mobilePhone.getText().toString())) {
                    ToastUtils.s(MobileLoginActivity.this,"请输入正确格式的手机号码");
                    return;
                }

                mPresenter.loginCode(mobilePhone.getText().toString().trim(),mobileCode.getText().toString().trim());
                break;
            case R.id.tv_mobile_password:   //密码登陆点击
                startActivity(new Intent(this, PasswordLoginActivity.class));
                break;
            case R.id.tv_mobile_wx_login:  //微信登录点击
                PlatformConfig.setWeixin("", "");
                if (MyApp.isWeixinAvilible(MobileLoginActivity.this)) {
                    WXEntryActivity.loginWeixin(MobileLoginActivity.this, MyApp.mWxApi);
                } else {
                    Toast.makeText(this, "请先安装微信", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    /**
     * 微信授权code回调
     * **/
    @Subscribe(threadMode = ThreadMode.POSTING)
    public void loginWechat(WeChatCodeEvent weChatCodeEvent) {
        if (EmptyUtil.isEmpty(weChatCodeEvent.getCode())) {
            Utils.toastMessage(this, "授权失败");
            return;
        }
        //请求检测APP微信登录是否绑定手机号
        mPresenter.checkBindPhone(weChatCodeEvent.getCode());

//        Intent intent = new Intent(this, MobileBindActivity.class);
//
//        startActivity(intent);

    }

    @Override
    protected void onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        super.onDestroy();
        mPresenter.detachView();
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {

        if (EmptyUtil.isEmpty(mobilePhone.getText().toString()) ||
                EmptyUtil.isEmpty(mobileCode.getText().toString())) {

            //mobileLogin.setClickable(false);
            mobileLogin.setBackground(
                    ContextCompat.getDrawable(this, R.drawable.password_login_button));
        } else {
           // mobileLogin.setClickable(true);
            mobileLogin.setBackground(
                    ContextCompat.getDrawable(this, R.drawable.oneclick_button));
        }
    }
}
